// analysis.js
import uCharts from '../../utils/u-charts/u-charts.js';
let uChartsInstance = {};
Page({
  data: {
    hiddenChart: false,
    legendData: ["盐","碘","糖","油"],
    realData: [90,110,165,195],
    recommendData: [190,210,105,35],
    oneDayData: [6.3,7,3.5,1.17],
    dataRange: '最新数据',
    userShow: false,
    userArray: ['成员1','成员2','成员3','成员4'],
    userChose: "成员1",
    userIndex: 0,
    dataArray: ['最新数据','最近一周','最近半个月', '最近一个月'],
    dataIndex: 0,
    show: false,
    cWidth: 750,
    cHeight: 500,
    pixelRatio: 2,
  
  },
  bindUserChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      userIndex: e.detail.value
    })
    this.getRemoteData()
  },
  bindDataChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      dataIndex: e.detail.value
    })
    this.getRemoteData()
  },
  onUserDisplay: function() {
    this.setData({ userShow: true });
  },
  onUserCancel: function() {
    this.setData({ userShow: false });
  },
  onUserClose: function() {
    this.setData({ userShow: false });
  },
  onUserConfirm: function(event) {
    this.setData({
      userShow: false,
      userChose: event.detail.value,
      userIndex: event.detail.index
    });
    console.log(this.data.dataIndex)
    this.getRemoteData()
  },
  onDisplay: function() {
    this.setData({ show: true });
  },
  onClose: function() {
    this.setData({ show: false });
  },
  onCancel: function() {
    this.setData({ show: false });
  },
  onConfirm: function(event) {
    this.setData({
      show: false,
      dataRange: event.detail.value,
      dataIndex: event.detail.index
    });
    console.log(this.data.dataIndex)
    this.getRemoteData()
  },
  onReady() {
    // this.getRemoteData()
    // console.log('[user] [analysis] onReady');
    // const cWidth = 750 / 750 * wx.getSystemInfoSync().windowWidth;
    // const cHeight = 500 / 750 * wx.getSystemInfoSync().windowWidth;
    // const pixelRatio = wx.getSystemInfoSync().pixelRatio;
    // this.setData({ cWidth, cHeight, pixelRatio });
    // this.getServerData();
    //这里的第一个 750 对应 css .charts 的 width
    // const cWidth = 750 / 750 * wx.getSystemInfoSync().windowWidth;
    // //这里的 500 对应 css .charts 的 height
    // const cHeight = 500 / 750 * wx.getSystemInfoSync().windowWidth;
    // this.setData({ cWidth, cHeight });
    // this.getServerData();
    this.getRemoteData()
    
  },
  getRemoteData() {
    console.log(11121)
    wx.cloud.callFunction({
      name: "getFoodData",
      success: res => {
        console.log(111)
        // output: res.result === 3
        console.log('获取远端摄入数据')
        console.log(res)
        if(this.data.dataIndex == 0) {
          var salt = res.result.data[0].salt
          var iodine = res.result.data[0].Iodine
          var sugar = res.result.data[0].sugar
          var oil =  res.result.data[0].oil
          this.setData({
            realData: [salt, iodine, sugar, oil],
            recommendData: this.data.oneDayData
          })
          this.getServerData()
        }
        if(this.data.dataIndex == 1) {
          var salt = 0
          var iodine = 0
          var sugar = 0
          var oil =  0
          for(var i = 0;i<7; i++) {
            salt += res.result.data[i].salt
            iodine += res.result.data[i].Iodine
            sugar += res.result.data[i].sugar
            oil +=  res.result.data[i].oil
          }
          this.setData({
            realData: [salt.toFixed(2), iodine.toFixed(2), sugar.toFixed(2), oil.toFixed(2)],
            recommendData: [this.data.oneDayData[0] * 7,this.data.oneDayData[1] * 7,this.data.oneDayData[2] * 7,this.data.oneDayData[3] * 7]
          })
          this.getServerData()
        }
        if(this.data.dataIndex == 2) {
          var salt = 0
          var iodine = 0
          var sugar = 0
          var oil =  0
          for(var i = 0;i<15; i++) {
            salt += res.result.data[i].salt
            iodine += res.result.data[i].Iodine
            sugar += res.result.data[i].sugar
            oil +=  res.result.data[i].oil
          }
          this.setData({
            realData: [salt.toFixed(2), iodine.toFixed(2), sugar.toFixed(2), oil.toFixed(2)],
            recommendData: [this.data.oneDayData[0] * 15,this.data.oneDayData[1] * 15,this.data.oneDayData[2] * 15,this.data.oneDayData[3] * 15]
          })
          this.getServerData()
        }
        if(this.data.dataIndex == 3) {
          var salt = 0
          var iodine = 0
          var sugar = 0
          var oil =  0
          for(var i = 0;i < 30; i++) {
            salt += res.result.data[i].salt
            iodine += res.result.data[i].Iodine
            sugar += res.result.data[i].sugar
            oil +=  res.result.data[i].oil
          }
          this.setData({
            realData: [salt.toFixed(2), iodine.toFixed(2), sugar.toFixed(2), oil.toFixed(2)],
            recommendData: [this.data.oneDayData[0] * 30,this.data.oneDayData[1] * 30,this.data.oneDayData[2] * 30,this.data.oneDayData[3] * 30]
          })
          this.getServerData()
        }
        // this.getServerData()
      },
      fail: err => {
        // handle error
      },
      complete: () => {
        // ...
      }
    })
  },
  getServerData() {
    // setTimeout(() => {
      //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
      let res = {
            categories: this.data.legendData,
            series: [
              {
                name: "实际摄入",
                data: this.data.realData
              },
              {
                name: "推荐摄入",
                data: this.data.recommendData
              }
            ]
          };
      this.drawCharts('KiPpifVeDVgXZAWrRhKmEXdEXzCqiuyj', res);
      this.drawCharts2('my-radar',res);

  },

  drawCharts(id, data) {
    const cWidth = 750 / 750 * wx.getSystemInfoSync().windowWidth;
    //这里的 500 对应 css .charts 的 height
    const cHeight = 500 / 750 * wx.getSystemInfoSync().windowWidth;
    this.setData({ cWidth, cHeight });
    const query = wx.createSelectorQuery().in(this);
    // const query = wx.createCanvasContext(id, this);
    query.select('#' + id).fields({ node: true, size: true }).exec(res => {
      if (res[0]) {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        canvas.width = res[0].width * this.data.pixelRatio;
        canvas.height = res[0].height * this.data.pixelRatio;
        uChartsInstance[id]=new uCharts({
            animation: true,
            background: "#FFFFFF",
            canvas2d: true,
            categories: data.categories,
            color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
            context: ctx,
            extra: {
              column: {
                type: "group",
                width: 30,
                activeBgColor: "#000000",
                activeBgOpacity: 0.08
              }
            },
            height: this.data.cHeight * this.data.pixelRatio,
            legend: {},
            padding: [15,15,0,5],
            pixelRatio: this.data.pixelRatio,
            series: data.series,
            type: "column",
            width: this.data.cWidth * this.data.pixelRatio,
            xAxis: {
              disableGrid: true
            },
            yAxis: {
              data: [
                {
                  min: 0
                }
              ]
            }
          });
      }else{
        console.error("[uCharts]: 未获取到 context");
      }
    });
  },
  drawCharts2(id,data){
    const ctx = wx.createCanvasContext(id, this);
    uChartsInstance[id] = new uCharts({
        type: "radar",
        context: ctx,
        width: this.data.cWidth,
        height: this.data.cHeight,
        categories: data.categories,
        series: data.series,
        animation: true,
        background: "#FFFFFF",
        color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
        padding: [5,5,5,5],
        dataLabel: false,
        legend: {
          show: true,
          position: "right",
          lineHeight: 25
        },
        extra: {
          radar: {
            gridType: "radar",
            gridColor: "#CCCCCC",
            gridCount: 3,
            opacity: 0.2,
            max: 200,
            border: true
          }
        }
      });
  },
  tap(e){
    uChartsInstance[e.target.id].touchLegend(e);
    uChartsInstance[e.target.id].showToolTip(e);
  },
  onLoad: function (options) {
    console.log('[user] [analysis] onLoad');
    
  },
  onShow: function () {
    
    console.log('[user] [analysis] onShow');
    // 读取本地数据
    this.setData({
      record: wx.getStorageSync('dataRecord')
    });
    console.log('[user] [analysis] Got record: ' + JSON.stringify(this.data.record));
  },
  onHide: function (){
    console.log('[user] [analysis] onHide');
  }
})
